import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, ScrollView, BackHandler } from "react-native";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { getQuestionById } from "@/mocks/questions";
import { useUserStore } from "@/store/user-store";
import { SimulationResult, UserAnswer, Question } from "@/types/question";
import { useTheme } from "@/hooks/useTheme";
import Button from "@/components/Button";

export default function SimulationResultsScreen() {
  const router = useRouter();
  const { colors } = useTheme();
  const { simulationId } = useLocalSearchParams<{ simulationId: string }>();
  const simulations = useUserStore((state) => state.simulations);
  const simulation = simulations.find((s) => s.id === simulationId);
  const [expandedQuestions, setExpandedQuestions] = useState<string[]>([]);
  const [questions, setQuestions] = useState<Record<string, Question>>({});
  
  // Load questions data
  useEffect(() => {
    if (simulation) {
      const loadQuestions = async () => {
        const loadedQuestions: Record<string, Question> = {};
        for (const questionId of simulation.questions) {
          const question = await getQuestionById(questionId);
          if (question) {
            loadedQuestions[questionId] = question;
          }
        }
        setQuestions(loadedQuestions);
      };
      loadQuestions();
    }
  }, [simulation]);
  
  React.useEffect(() => {
    // Prevent going back with hardware back button
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        router.replace("/tabs");
        return true;
      }
    );
    return () => backHandler.remove();
  }, []);
  
  if (!simulation) {
    return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <Text style={[styles.errorText, { color: colors.text }]}>未找到模拟结果</Text>
        <Button
          title="返回首页"
          onPress={() => router.replace("/")}
          variant="outline"
        />
      </View>
    );
  }
  
  const toggleQuestion = (questionId: string) => {
    setExpandedQuestions((prev) =>
      prev.includes(questionId)
        ? prev.filter((id) => id !== questionId)
        : [...prev, questionId]
    );
  };
  
  const formatDate = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };
  
  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    return `${minutes} minute${minutes !== 1 ? "s" : ""}`;
  };
  
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <Stack.Screen
        options={{
          title: "模拟结果",
          headerStyle: {
            backgroundColor: colors.background,
          },
          headerTintColor: colors.text,
          headerBackVisible: false,
        }}
      />
      <ScrollView style={styles.content}>
        <View style={styles.header}>
          <View style={[styles.iconContainer, { backgroundColor: "rgba(99, 102, 241, 0.1)" }]}>
            <Ionicons name="trophy" size={48} color={colors.primary} />
          </View>
          <Text style={[styles.title, { color: colors.text }]}>面试完成！</Text>
          <Text style={[styles.subtitle, { color: colors.subtext }]}>
            你已完成模拟面试。以下是你的表现：
          </Text>
        </View>
        <View style={styles.statsContainer}>
          <View style={[styles.statCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
            <Ionicons name="calendar-outline" size={20} color={colors.primary} />
            <Text style={[styles.statLabel, { color: colors.subtext }]}>日期</Text>
            <Text style={[styles.statValue, { color: colors.text }]}>{formatDate(simulation.date)}</Text>
          </View>
          <View style={[styles.statCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
            <Ionicons name="time-outline" size={20} color={colors.primary} />
            <Text style={[styles.statLabel, { color: colors.subtext }]}>时长</Text>
            <Text style={[styles.statValue, { color: colors.text }]}>
              {formatDuration(simulation.duration)}
            </Text>
          </View>
          <View style={[styles.statCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
            <Ionicons name="checkmark-circle-outline" size={20} color={colors.primary} />
            <Text style={[styles.statLabel, { color: colors.subtext }]}>问题数</Text>
            <Text style={[styles.statValue, { color: colors.text }]}>{simulation.questions.length}</Text>
          </View>
        </View>
        <Text style={[styles.sectionTitle, { color: colors.text }]}>回答列表</Text>
        {simulation.questions.map((questionId, index) => {
          const question = questions[questionId];
          const answer = simulation.answers.find(
            (a) => a.questionId === questionId
          );
          const isExpanded = expandedQuestions.includes(questionId);
          if (!question || !answer) return null;
          return (
            <View key={questionId} style={[styles.questionCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <Text style={[styles.questionNumber, { color: colors.primary }]}>问题 {index + 1}</Text>
              <Text style={[styles.questionText, { color: colors.text }]}>{question.question}</Text>
              <Button
                title={isExpanded ? "隐藏回答" : "显示回答"}
                variant="outline"
                size="small"
                onPress={() => toggleQuestion(questionId)}
              />
              {isExpanded && (
                <View style={[styles.answerContainer, { backgroundColor: "rgba(255, 255, 255, 0.05)" }]}>
                  <Text style={[styles.answerLabel, { color: colors.text }]}>你的回答:</Text>
                  <Text style={[styles.answerText, { color: colors.subtext }]}>
                    {answer.userAnswer || "(No answer provided)"}
                  </Text>
                  <Text style={[styles.answerLabel, { color: colors.text }]}>参考答案:</Text>
                  <Text style={[styles.answerText, { color: colors.subtext }]}>{question.answer}</Text>
                </View>
              )}
            </View>
          );
        })}
      </ScrollView>
      <View style={styles.footer}>
        <Button
          title="返回主页"
          onPress={() => router.replace("/")}
          fullWidth
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  header: {
    alignItems: "center",
    marginBottom: 24,
  },
  iconContainer: {
    width: 96,
    height: 96,
    borderRadius: 48,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    marginBottom: 8,
    textAlign: "center",
  },
  subtitle: {
    fontSize: 16,
    textAlign: "center",
    paddingHorizontal: 24,
  },
  statsContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 24,
  },
  statCard: {
    flex: 1,
    borderRadius: 12,
    padding: 16,
    alignItems: "center",
    marginHorizontal: 4,
    borderWidth: 1,
  },
  statLabel: {
    fontSize: 14,
    marginTop: 8,
    marginBottom: 4,
  },
  statValue: {
    fontSize: 16,
    fontWeight: "600",
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 16,
  },
  questionCard: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    borderWidth: 1,
  },
  questionNumber: {
    fontSize: 14,
    fontWeight: "600",
    marginBottom: 8,
  },
  questionText: {
    fontSize: 16,
    marginBottom: 16,
  },
  answerContainer: {
    marginTop: 16,
    borderRadius: 8,
    padding: 12,
  },
  answerLabel: {
    fontSize: 14,
    fontWeight: "600",
    marginBottom: 4,
  },
  answerText: {
    fontSize: 14,
    marginBottom: 16,
  },
  footer: {
    padding: 16,
  },
  errorText: {
    fontSize: 18,
    textAlign: "center",
    marginTop: 24,
    marginBottom: 16,
  },
});
